package com.youmingxing.network;

import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

import com.loopj.android.http.JsonHttpResponseHandler;
import com.youmingxing.AllStarApp;
import com.youmingxing.data.GlobalDataManager;
import com.youmingxing.dialog.LoginDialog;
import com.youmingxing.view.DialogManager;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONObject;

/**
 * @author evilyin(ChenZhixi)
 * @since 15/10/19
 */
public class BaseJsonHandler extends JsonHttpResponseHandler {

    private Context context;

    public BaseJsonHandler(Context context) {
        if (context != null) {
            this.context = context;
        } else {
            this.context = AllStarApp.getInstance();
        }
    }

    @Override
    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
        if (response.optInt("status") != 200) {
            if (response.optInt("status") == 40063) {
//                onFail(40063, "您还未登录,请先登录!");
                onFail(40063, "");
                GlobalDataManager.token = "";
                GlobalDataManager.userInfo = "";
                GlobalDataManager.save();
                Intent intent = new Intent(context,LoginDialog.class);
                context.startActivity(intent);
            } else {
                onFail(response.optInt("status"), response.optString("statusText"));
            }
        } else {
            onSuccessWithData(response);
        }
        DialogManager.dismissDialog();
    }

    public void onSuccessWithData(JSONObject response) {

    }

    /**
     * 请求失败
     * @param statusCode http错误时为http错误码,返回有内容时为status码
     * @param statusText http错误时为空字符串,返回有内容时为statusText
     */
    public void onFail(int statusCode, String statusText) {
        if (statusText.equals("")) {
//            Toast.makeText(context, "加载失败,错误码:" + statusCode,Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(context, statusText,Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
        onFail(statusCode,"");
        DialogManager.dismissDialog();
    }

    @Override
    public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) {
        onFail(statusCode,"");
        DialogManager.dismissDialog();
    }

    @Override
    public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
        onFail(statusCode,"");
        DialogManager.dismissDialog();
    }

    public void showToast(String message) {
        Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
    }

    public void showToast(int res) {
        Toast.makeText(context, res, Toast.LENGTH_SHORT).show();
    }
}
